package com.wxc.service.impl;

import com.wxc.contants.Constant;
import com.wxc.entity.SysUser;
import com.wxc.exception.BusinessException;
import com.wxc.mapper.SysUserMapper;
import com.wxc.service.UserService;
import com.wxc.utils.PasswordUtils;
import com.wxc.utils.token.JwtTokenUtil;
import com.wxc.vo.REnum;
import com.wxc.vo.req.LoginReqVO;
import com.wxc.vo.resp.LoginRespVO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wxc
 * @date 2021年10月24日 13:18
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public LoginRespVO login(LoginReqVO loginReqVO) {
        // userMapper.selectByPrimaryKey();
        SysUser user = userMapper.selectByUsername(loginReqVO.getUsername());

        if (user == null) throw new BusinessException(REnum.LOGIN_ERROR);
        if (Constant.ACCOUNT_LOCK.equals(user.getStatus()))
            throw new BusinessException(REnum.ACCOUNT_DISABLE_ERROR);
        if (!PasswordUtils.matches(user.getSalt(), loginReqVO.getPassword(), user.getPassword()))
            throw new BusinessException(REnum.LOGIN_ERROR);

        // 校验通过 发送token
        LoginRespVO respVO = new LoginRespVO();
        BeanUtils.copyProperties(user, respVO);

        Map<String, Object> claims = new HashMap<>();
        // claims.put(Constant.JWT_PERMISSIONS_KEY, getPermissionsByUserId(sysUser.getId()));
        // claims.put(Constant.JWT_ROLES_KEY, getRolesByUserId(sysUser.getId()));
        claims.put(Claims.ID, user.getId());
        // claims.put(Claims.SUBJECT, user.getUsername());
        String access_token = JwtTokenUtil.generateToken(claims);
        // Map<String, Object> refreshTokenClaims = new HashMap<>();
        // refreshTokenClaims.put(Constant.JWT_USER_NAME, sysUser.getUsername());
        // if (vo.getType().equals("1")) {
        //     refresh_token = JwtTokenUtil.getRefreshToken(sysUser.getId(), refreshTokenClaims);
        // } else {
        //     refresh_token = JwtTokenUtil.getRefreshAppToken(sysUser.getId(), refreshTokenClaims);
        // }
        respVO.setAccessToken(access_token);
        // respVO.setRefreshToken(refresh_token);


        return respVO;
    }
}
